<?php


namespace App\Http\Controllers\Business;


use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Resources\PaginationCollection;
use App\Http\Service\DeviceService;
use App\Jobs\CheckOrder;
use App\Model\Agent;
use App\Model\Business;
use App\Model\Contract;
use App\Model\Country;
use App\Model\Device;
use App\Model\DeviceLog;
use App\Model\Repair;
use App\User;
use App\Utils\Result;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\Model\BusinessConf;
use App\Model\Bill;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class DeviceController extends Controller
{

    /**下拉菜单设备列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selfList(Request $request){
        $id = $request->input('id');
        $businessId = $this->getBusinessId();
        $list = DB::table('device')
            ->where(function ($query) use ($id) {
                $query->where('id', $id)
                    ->orWhere('house_id', '<=', 0);
            })
            ->where(function ($query) use ($businessId) {
                $query->where('business_id',$businessId );
                $query->whereNull('deleted_at');
            })
            ->get();
        return Result::success($list);
    }



    public function index(Request $request)
    {
        $page = $request->input('page', 1);
        // Get the number of houses to show per page
        $perPage = 20;
        $keyword = $request->input('keyword');
        $houseId = $request->input('houseId');
        $status = $request->input('status');
        $query = Device::query();
        /**
         * 改造后
         */
        $query->leftJoin('house', 'device.house_id', '=', 'house.id');
        $query->where('device.business_id', $this->getBusinessId());
        $query->when($keyword, function ($q) use ($keyword) {
            $q->where(function ($q) use ($keyword) {
                // Assuming 'houses' is the correct table name for the 'house' relationship
                $q->where('house.estate_name', 'like', "%{$keyword}%")
                    ->orWhere('house.name', 'like', "%{$keyword}%")
                    ->orWhere('device.sn', 'like', "%{$keyword}%");
            });
        });
        $query->when($houseId, function ($q) use ($houseId) {
            $q->where('device.house_id', $houseId);
        });
        if (in_array($status, [1, 2])) {
            $query->where('device.status', $status);
        }
        if ($status == 3) {
            $query->where('device.online_status', 2);
        }
        if ($status == 4) {
            $query->where('device.ems_status', 1);
        }
        if ($status == 5) {
            $query->where('device.low', '>', 0)->whereColumn('device.low', '>', 'device.du');
        }
        $query->select('device.*');
        $query->orderBy('house.estate_name', 'asc')->orderBy('house.name', 'asc');
        $data = $query
            ->with('house', 'house.fastContract') // Load the house relationship
            ->paginate($perPage, ['*'], 'page', $page);
//        foreach($country as $v){
//            if (strpos($data->house->estate_name, $v) !== false) {
//                $data->need_people = 1;
//                break;
//            }
//        }
//        foreach($data as $k => &$v){
//            if($v->qrcode == '[]'){
//                $v->qrcode = '';
//            }
//        }
        return Result::success(new PaginationCollection($data));
    }

    public function detail($id)
    {
        $device = Device::with('house', 'rate', 'business', 'business.user')->find($id);

        if (!$device) {
            return Result::success($device);
        }
        $business = Business::query()->where('id',$device->business_id)->first();
        if(!$business){
            $device->need_people  = 0;
        }else{
            $user = User::query()->where('id',$business->user_id)->first();
            $device->need_people  = $user->gongan;
        }
//        if ($device->house && $user->gongan == 1) {
//            $country = Country::query()->get();
//            foreach ($country as $v) {
//                if ($v->province == $device->house->province && $v->city == $device->house->city) {
//                    if ($device->house->district) {
//                        if ($v->district == $device->house->district) {
//                            if($device->house->country && $device->house->country == $v->country){
//                                if($v->name){
//                                    if (strpos($device->house->estate_name, $v->name) !== false) {
//                                        $device->need_people = $v->type;
//                                        break;
//                                    }
//                                }else{
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            }else{
//                                if (strpos($device->house->estate_name, $v->name) !== false) {
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            }
//                        }
//                    } else {
//                        if($device->house->country && $device->house->country == $v->country){
//                            if($v->name){
//                                if (strpos($device->house->estate_name, $v->name) !== false) {
//                                    $device->need_people = $v->type;
//                                    break;
//                                }
//                            }else{
//                                $device->need_people = $v->type;
//                                break;
//                            }
//                        }else{
//                            if (strpos($device->house->estate_name, $v->name) !== false) {
//                                $device->need_people = $v->type;
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//        }
        $device->can_recharge = 1;
        if ($device->business_id) {
            $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
            // 账号逾期充值限制
            if ($businessConf && $businessConf->is_limit_recharge_days > 0) {
                $failBillCount = Bill::query()->where('house_id', $device->house_id)->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->where('pay_date', '<', Carbon::now()->subDays($businessConf->is_limit_recharge_days)->toDateString())
                    ->count();
                if ($failBillCount > 0) {
                    $device->can_recharge = 0;
                }
            }
        }
        if ($device->qrcode == '[]') {
            $device->qrcode = '';
        }
        return Result::success($device);
    }

    /**手机号分享
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shareMobile(Request $request)
    {
        $mobile = $request->input('mobile');
        if (!$mobile) {
            return Result::error(404, '请填写手机号');
        }
        $sn = $request->input('sn');
        Device::query()->where('mobile', $mobile)->update(['mobile' => '']);
        $device = Device::where('sn', $sn)->first();
        if (!$device) {
            return Result::error(404, '设备号不存在');
        }
        if (Contract::query()->where('house_id', $device->house_id)->where('status', '<=', ContractStatus::YIQIANYUE)->exists()) {
            return Result::error(402, '此房源已存在合同');
        }
        $device->mobile = $mobile;
        $device->save();
        $user = User::where('mobile', $mobile)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $mobile;
            $user->type = 'tenant';
            $user->password = Hash::make(substr((string)$mobile, 5));
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        return Result::success();
    }

    # 临时设备列表
    public function tempDeviceList()
    {
        $user = $this->getUser();
        $data = $user->devices()->get();
        return Result::success($data);
    }

    public function getDeviceListByIds(Request $request)
    {
        $ids = $request->input('ids');
        $data = Device::query()->whereIn('id', $ids)->with('house')->get();
        return Result::success($data);
    }

    # 添加临时设备
    public function tempDeviceAdd(Request $request)
    {
        $id = $request->input('id');
        $sn = $request->input('sn');
        $user = $this->getUser();
        if ($id) {
            $user->devices()->attach($id);
        } elseif ($sn) {
            $device = Device::query()->where('sn', $sn)->first();
            $user->devices()->attach($device->id);
        }

        return Result::success([]);
    }


    // 设备日志
    public function log(Request $request, $id)
    {
        $page = $request->input('page', 1);
        $perPage = 20;
        $query = DeviceLog::query();
        $data = $query->orderByDesc('id')
            ->where('device_id', $id)
            ->where('action', $request->input('action', 1))
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new PaginationCollection($data));
    }

    public function search(Request $request)
    {
        $sn = $request->input('sn');
        $sn = trim($sn);
        $device = Device::with('house', 'rate', 'business', 'business.user')->where('sn', $sn)->first();
        if (!$device) {
            return Result::error(404, '设备不存在');
        }

        $device->can_recharge = 1;

        if ($device->business_id) {
            $businessConf = BusinessConf::query()->where('business_id', $device->business_id)->first();
            // 账号逾期充值限制
            if ($businessConf && $businessConf->is_limit_recharge_days > 0) {
                $failBillCount = Bill::query()->where('house_id', $device->house_id)->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->where('pay_date', '<', Carbon::now()->subDays($businessConf->is_limit_recharge_days)->toDateString())
                    ->count();
                if ($failBillCount > 0) {
                    $device->can_recharge = 0;
                }
            }
        }

        return Result::success($device);
    }

    public function create(Request $request)
    {
        $user = $this->getUser();
        $deviceModel = Device::query()->where('sn', $request->input('sn'))->with('house')->first();
        if ($deviceModel && $deviceModel->house_id) {
            return Result::error(401, '设备已被绑定，无法重复绑定');
        }
        if (!$deviceModel) {
            return Result::error(401, '设备不存在');
            /*$deviceModel = new Device();
            $deviceModel->fill($request->all());
            $deviceModel->bind_at = Carbon::now()->toDateTimeString();
            $deviceModel->expired_at = Carbon::now()->addYears(8)->toDateTimeString();*/
        }
        if( $request->input('price') > 3  && $deviceModel->type != 2){
            return Result::error(401, '电量单价不可超过3元');
        }
        if( $request->input('price') > 10 && $deviceModel->type == 2){
            return Result::error(401, '水费单价不可超过3元');
        }
        $business = Business::query()->where('user_id', $user->id)->first();
        if ($business->agent_id) {
            if ($business->agent_id != $deviceModel->agent_id && $deviceModel->type != 2) {
                $agent = Agent::query()->where('id',$business->agent_id)
                    ->first();
                $str = '绑定异常，请联系您的专属客服';
                if($agent){
                    if($agent->tel_no){
                        $str .= ":({$agent->tel_no})";
                    }else{
                        $str .= ":({$agent->mobile})";
                    }
                }
                return Result::error(401, $str);
            }
        } else {
            $business->agent_id = $deviceModel->agent_id;
            $business->save();
        }
        $deviceModel->house_id = $request->input('house_id');
        if( $request->input('price') > 3){
            return Result::error(401, '电量单价不可超过3元');
        }
        $deviceModel->price = $request->input('price');
        $deviceModel->alias = $request->input('alias');
        $deviceModel->business_id = $this->getBusinessId();
        $deviceModel->bind_at = Carbon::now()->toDateTimeString();

        if (!$deviceModel->expired_at) {
            $deviceModel->expired_at = Carbon::now()->addYears(10)->toDateTimeString();
        }

        $deviceModel->save();

        return Result::success($deviceModel);
    }

    public function update(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        //$deviceModel->fill($request->all());

        if ($request->input('house_id')) {
            $deviceModel->house_id = $request->input('house_id');
        }
        if ($request->input('low') != false) {
            $deviceModel->low = $request->input('low');
        }
        if ($request->input('price') != false) {
            if( $request->input('price') > 3 && $deviceModel->type != 2){
                return Result::error(401, '电量单价不可超过3元');
            }
            if( $request->input('price') > 10 && $deviceModel->type == 2){
                return Result::error(401, '水费单价不可超过10元');
            }
            $deviceModel->price = $request->input('price');
        }
        $deviceModel->save();
        $deviceModel->load('house');
        return Result::success($deviceModel);
    }

    public function unbind($id)
    {
        $deviceModel = Device::query()->where('business_id', $this->getBusinessId())->find($id);
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $deviceModel->house_id = 0;
        $deviceModel->save();

        return Result::success();
    }

    /**修改公摊
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function speedLog(Request $request)
    {
        $user = $this->getUser();
        $deviceId = $request->input('device_id', 0);
        $deviceModel = Device::query()->where('id', $deviceId)->first();
        $speed = $request->input('speed');
        try {
            DeviceLog::create(
                [
                    'action' => 6,
                    'device_id' => 'device_id',
                    'log' => '读取的公摊损耗:' . $deviceModel->speed . '，修改的损耗:' . $speed,
                    'user_id' => $user->id
                ]
            );
            return Result::success();
        } catch (\Exception $e) {
            return Result::error('1001', '操作繁忙');
        }
    }

    public function read(Request $request, $id)
    {
        $deviceModel = Device::where('id', $id)->first();
        $before = $deviceModel->du;
        $deviceModel->fill($request->all());
        $deviceModel->read_at = now()->toDateTimeString();
        $deviceModel->save();
        $service = app()->make(DeviceService::class);
//        try {
//            DeviceLog::create(
//                [
//                    'action' => 5,
//                    'device_id' => $deviceModel->id,
//                    'log' => '抄表后余量:' . $deviceModel->du . '，总电量:' . $deviceModel->total,
//                    'user_name' => $service->getUserName(),
//                    'before' => $before,
//                    'after' => $deviceModel->du
//                ]
//            );
//        } catch (\Exception $e) {
//            Log::info($e->getMessage());
//        }
        return Result::success($deviceModel);
    }

    public function destroy($id)
    {
        $deviceModel = Device::where('id', $id)->where('business_id', $this->getBusinessId())->first();
        if ($deviceModel) {
            //$deviceModel->delete();
            $deviceModel->business_id = 0;
            $deviceModel->house_id = 0;
            $deviceModel->save();
        }
        return Result::success();
    }

    # 拉闸
    public function stop(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->stop($request->input('mac'));

        return Result::success();
    }

    # 合闸
    public function start(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->start($request->input('mac'));

        return Result::success();
    }

    # 充值
    public function recharge(Request $request)
    {
        $isRecharged = $request->input('isRecharged') ?? 0;
        $isPaid = $request->input('isPaid') ?? 0;
        $deviceModel = Device::where('mac', trim($request->input('mac')))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
//        if($deviceModel->signal == 0){
//            return Result::error(1001, '当前设备暂无信号');
//        }
        // todo 验证支付单
        $service = app()->make(DeviceService::class);
        $result = $service->recharge(trim($request->input('mac')), $request->input('du'), $request->input('amount'), $isRecharged, $isPaid);
        return Result::success();
    }

    # 清0
    public function clear(Request $request)
    {
        $user = $this->getUser();
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->clear($request->input('mac'));
        return Result::success();
    }

    # 调表计量系数
    public function speed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->speed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }

    # 读表计量系数
    public function querySpeed(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->querySpeed($request->input('mac'), $request->input('speed', 1));

        return Result::success();
    }

    public function statusQuery(Request $request)
    {
        Log::notice('statusQuery', $request->all());
        $deviceModel = Device::where('mac', $request->input('mac'))->where('business_id', $this->getBusinessId())->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->statusQuery($request->input('mac'));

        return Result::success();
    }

    public function restart(Request $request)
    {
        $deviceModel = Device::where('mac', $request->input('mac'))->first();
        if (!$deviceModel) {
            return Result::error(404, '设备不存在');
        }
        $service = app()->make(DeviceService::class);
        $result = $service->restart($request->input('mac'));
        return Result::success();
    }
}
